package cn.cloudtogo.server.mysql.controller;

import cn.cloudtogo.common.types.RequestHeaderObject;
import cn.cloudtogo.common.types.Result;
import cn.cloudtogo.support.mysql.column.ColumnApi;
import cn.cloudtogo.support.mysql.column.ColumnDefinition;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import static cn.cloudtogo.server.WebResponse.accepted;
import static cn.cloudtogo.server.WebResponse.created;

/**
 * @author yaolianhua789@gmail.com
 **/
@RestController
@RequestMapping("/columns")
public class TableColumnsController {

    private final ColumnApi columnApi;

    public TableColumnsController(ColumnApi columnApi) {
        this.columnApi = columnApi;
    }

    @PostMapping
    public ResponseEntity<Result<Void>> add(@RequestBody ColumnDefinition definition,
                                            @RequestParam String table,
                                            @ApiIgnore RequestHeaderObject requestHeaderObject) {
        columnApi.add(requestHeaderObject, table, definition);
        return created();
    }

    @PutMapping
    public ResponseEntity<Result<Void>> update(@RequestBody ColumnDefinition definition,
                                               @RequestParam String table,
                                               @RequestParam(value = "newColumnName", required = false) String name,
                                               @ApiIgnore RequestHeaderObject requestHeaderObject) {
        columnApi.update(requestHeaderObject, table, definition, name);
        return accepted();
    }

    @DeleteMapping("/{column}")
    public ResponseEntity<Result<Void>> delete(@PathVariable String column,
                                               @RequestParam String table,
                                               @ApiIgnore RequestHeaderObject requestHeaderObject) {
        columnApi.delete(requestHeaderObject, table, column);
        return accepted();
    }

}
